<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-07-22 14:10
 *
 * Version: 2.0
 */

namespace App\Modules\Store\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;
use Illuminate\Support\Facades\DB;

class GetMostPopularStoresCriteria extends BaseCriterias
{
    protected $adcode;

    public function __construct($adcode)
    {
        $this->adcode = $adcode;
    }

    public function apply($model, RepositoryInterface $repository)
	{
        $adcode = $this->adcode;
        $adcode =substr($adcode,0,3);

		$store_resource_query = DB::table('store_resource')
			->selectRaw('count(*) as store_resource_num,store_id')
			->where('type',1)
			->groupBy('store_id');


	    return $model->select(['id','name','logo'])
            ->with('picture:id,image','storeResource')
		    ->withCount(['comment as good_comment_count' =>function($query){
                $query->where('order_comment.is_goods','=','1');
            },'comment as all_comment_count', 'storeLike as fansNum'])
//		    ->withCount(['storeResource'=>function($v){
//		    	$v->where('type','=',1);
//		    }])
		    ->leftJoin(\DB::raw("({$store_resource_query->toSql()}) as hx_store_resource"), function ($join) use ($store_resource_query) {
			    $join->mergeBindings($store_resource_query)->on('store.id', '=', 'store_resource.store_id');
		    })
            ->where('store_resource.store_resource_num','>=',3)
            ->where('store.adcode','like','%'.$adcode.'%')
            ->orderBy('fansNum', 'desc');



//		$select = implode([
//			'hx_store.id',
//			'hx_store.name as storeName',
//			'hx_picture.image as storeLogo'
//		],',');
//		return $model->selectRaw($select)
//			->withCount(['storeLike as fansNum'])
//			->leftJoin('picture','store.logo','picture.image')
//			->withCount(['comment as good_comment_count' =>function($query){
//				$query->where('order_comment.is_goods','=','1');
//			},'comment as all_comment_count'])
//			->with(['storeResource' => function ($query) {
//				$select = [
//					'hx_store_resource.id',
//					'hx_store_resource.store_id',
//					'hx_store_resource.resource',
//					'type',
//					'CASE WHEN type = 1 THEN hx_picture.image else hx_video.thumb END as image',
//					'CASE WHEN type = 1 THEN null else hx_video.url END as video',
//				];
//				$select = implode($select, ',');
//
//				$query->selectRaw($select)
//					->leftJoin('picture',function ($join){
//						$join->on('store_resource.resource','=','picture.id');
//					})
//					->leftJoin('video',function ($join){
//						$join->on('store_resource.resource','=','video.id');
//
//					})
//				;
//			}])
//			->orderBy('fansNum', 'desc');
	}
}
